package com.qiqijuice.sales;

import net.miginfocom.swt.MigLayout;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableItem;

public class OrderItemsView extends Composite {
	public static int EVT_MODIFY_ORDER = 0x9000;
	public static int EVT_DELETE_ITEM = 0x9001;
	
	Order order;
	Table table;
	Label total;
	
	public OrderItemsView(Composite parent) {
		super(parent, SWT.None);

		MigLayout layout = new MigLayout("debug, wrap 2","[][100!]", "[grow][]");
		setLayout(layout);
		
		table = new Table(this, SWT.NONE);
		table.setLayoutData("grow, width 100%");
		
		Button b = new Button(this, SWT.PUSH);
		b.setText("Quantity");
		b.setLayoutData("cell 1 0, flowy, ay t, width 100%, height 100, sg 1");
		b.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				if (table.getSelectionCount() > 0) {
					Event ee = new Event();
					ee.data = table.getSelection()[0].getData();
					notifyListeners(EVT_MODIFY_ORDER, ee);
				}
			}
			
		});

		b = new Button(this, SWT.PUSH);
		b.setText("Delete");
		b.setLayoutData("cell 1 0, sg 1");
		b.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (table.getSelectionCount() > 0) {
					Event ee = new Event();
					ee.data = table.getSelection()[0].getData();
					notifyListeners(EVT_DELETE_ITEM, ee);
				}
			}
		});
		
		Label l = new Label(this, SWT.NONE);
		l.setLayoutData("span 2, growx, height 50:100:n");
		total = l;
		total.setText("Total: ");
		pack();
	}

	public void updateItems() {
		table.removeAll();
		float orderTotal = 0;
		if (order != null) {
			OrderItem[] items = order.getOrderItems();
			for (OrderItem i : items) {
				if (!i.isRemoved()) {
					TableItem ti = new TableItem(table, SWT.NONE);
					ti.setData(i);
					Product p = i.getProduct();
					float sub = p.getPrice() * i.getQuantity();
					String desc = String.format("%s   @%.2f   X   %.2f  -  %.2f", p.getName(), p.getPrice(), i.getQuantity(), sub);
					ti.setText(desc);
					orderTotal += sub;
				}
			}
		}
		
		total.setText("Total: " + String.format("%.2f", orderTotal));
		System.out.println("Total: " + String.format("%.2f", orderTotal));
		total.update();
	}

	public void viewOrder(Order order) {
		this.order = order;
		updateItems();
	}

	public Order getOrder() {
		return order;
	}
}
